import fs from 'fs'
import path from 'path'
import glob from 'fast-glob'
// import { docRoot, docsDirName, projRoot } from '@element-plus/build-utils'
// import { REPO_BRANCH, REPO_PATH } from '@element-plus/build-constants'
// import { getLang, languages } from '../utils/lang'
// import footerLocale from '../i18n/component/footer.json'

import type { Plugin } from 'vite'

const projRoot = path.resolve(__dirname, '..', '..')
const docsRoot = path.resolve(projRoot, 'docs')

type Append = Record<'headers' | 'footers' | 'scriptSetups', string[]>

let compPaths: string[]

export function MarkdownTransform(): Plugin {
  let root = ''
  return {
    name: 'element-plus-md-transform',

    enforce: 'pre',

    // async buildStart() {
    //   const pattern = `{${[...languages, languages[0]].join(',')}}/component`

    //   compPaths = await glob(pattern, {
    //     cwd: docsRoot,
    //     absolute: true,
    //     onlyDirectories: true,
    //   })
    // },
    configResolved(resolvedConfig) {
      root = resolvedConfig.root;
    },

    async transform(code, id) {
      if (!id.endsWith('.md')) return
      const m = code.match(/:::demo /)
      if (!m?.length) return;

      // const componentId = path.basename(id, '.md')
      const componentId = id.replace(root, '').replace('/', '').replace('.md', '');
      // console.log('chenyf', id, root, componentId)
      
      const append: Append = {
        headers: [],
        footers: [],
        scriptSetups: [
          `const demos = import.meta.glob('/../../examples/${componentId}/**/*.vue', { eager: true });`,
        ],
      }

      code = transformVpScriptSetup(code, append)

      // if (compPaths.some((compPath) => id.startsWith(compPath))) {
      //   code = transformComponentMarkdown(id, componentId, code, append)
      // }

      return combineMarkdown(
        code,
        [combineScriptSetup(append.scriptSetups), ...append.headers],
        append.footers
      )
    },
  }
}

const combineScriptSetup = (codes: string[]) =>
  `\n<script setup>
${codes.join('\n')}
</script>
`

const combineMarkdown = (
  code: string,
  headers: string[],
  footers: string[]
) => {
  const frontmatterEnds = code.indexOf('---\n\n')
  const firstHeader = code.search(/\n#{1,6}\s.+/)
  const sliceIndex =
    firstHeader < 0
      ? frontmatterEnds < 0
        ? 0
        : frontmatterEnds + 4
      : firstHeader

  if (headers.length > 0)
    code =
      code.slice(0, sliceIndex) + headers.join('\n') + code.slice(sliceIndex)
  code += footers.join('\n')

  return `${code}\n`
}

const vpScriptSetupRE = /<vp-script\s(.*\s)?setup(\s.*)?>([\s\S]*)<\/vp-script>/

const transformVpScriptSetup = (code: string, append: Append) => {
  const matches = code.match(vpScriptSetupRE)
  if (matches) code = code.replace(matches[0], '')
  const scriptSetup = matches?.[3] ?? ''
  if (scriptSetup) append.scriptSetups.push(scriptSetup)
  return code
}

